package c04.thread.safe;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/*
测试脚本
- windows:
for /L %n in (1,1,10) do java -cp ".;D:\repository\m2\ch\qos\logback\logback-
classic\1.2.3\logback-classic-1.2.3.jar;D:\repository\m2\ch\qos\logback\logback-
core\1.2.3\logback-core-1.2.3.jar;D:\repository\m2\org\slf4j\slf4j-
api\1.7.25\slf4j-api-1.7.25.jar" c04.thread.safe.ExerciseSell

- linux
for i in {1..10} do; \
java -cp ".:$HOME/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar:$HOME/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:$HOME/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar" c04.thread.safe.ExerciseSell \
done
 */
@Slf4j(topic = "c.ExerciseSell")
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        // 模拟多人买票
        TicketWindow window = new TicketWindow(1000);
        // 所有线程的集合
        List<Thread> threadList = new ArrayList<>();
        // 卖出的票数统计（vector是list的线程安全实现）
        List<Integer> amountList = new Vector<>();

        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                // 售票
                int amount = window.sell(random(5));
                // 统计售票数
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }

        // 主线程必须等待所有售票线程执行完再去统计卖出去的票数
        for (Thread thread : threadList) {
            thread.join();
        }

        // 统计卖出的票数和剩余票数
        log.debug("余票：{}",window.getCount());
        log.debug("卖出的票数：{}", amountList.stream().mapToInt(i-> i).sum());
    }

    // Random 为线程安全
    static Random random = new Random();

    // 随机 1~5
    public static int random(int amount) {
        return random.nextInt(amount) + 1;
    }
}

// 售票窗口
class TicketWindow {
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    // 获取余票数量
    public int getCount() {
        return count;
    }

    // 售票
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}